package com.qyhl.school.school.home.newhome;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qyhl.school.R;
import com.qyhl.school.R2;
import com.qyhl.school.school.SchoolHomeActivity;
import com.qyhl.school.school.home.SchoolGridViewAdapter;
import com.qyhl.school.school.home.SchoolMainContract;
import com.qyhl.school.school.home.SchoolMainPresenter;
import com.qyhl.webtv.basiclib.base.BaseFragment;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.live.TeleTextBean;
import com.qyhl.webtv.commonlib.entity.news.NewsBean;
import com.qyhl.webtv.commonlib.entity.school.SchoolListBean;
import com.qyhl.webtv.commonlib.entity.school.SchoolMainBean;
import com.qyhl.webtv.commonlib.entity.school.SchoolVlogBean;
import com.qyhl.webtv.commonlib.service.UserService;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.commonlib.utils.view.gridviewpager.GridViewPager;
import com.qyhl.webtv.commonlib.utils.view.gridviewpager.GridViewPagerDataAdapter;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.stx.xhb.androidx.XBanner;
import com.stx.xhb.androidx.transformers.Transformer;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import es.dmoral.toasty.Toasty;

public class SchoolNewMainFragment extends BaseFragment implements SchoolMainContract.SchoolMainView {
    @BindView(R2.id.banner)
    XBanner banner;
    @BindView(R2.id.highlight_layout)
    RelativeLayout highlightLayout;
    @BindView(R2.id.highlight_recycler)
    RecyclerView highlightRecycler;
    @BindView(R2.id.highlight_content)
    RelativeLayout highlightContent;
    @BindView(R2.id.column_layout)
    RelativeLayout columnLayout;
    @BindView(R2.id.reporter_cover)
    RoundedImageView reporterCover;
    @BindView(R2.id.reporter_tag)
    ImageView reporterTag;
    @BindView(R2.id.reporter_num)
    TextView reporterNum;
    @BindView(R2.id.reporter_title)
    TextView reporterTitle;
    @BindView(R2.id.reporter_sign)
    TextView reporterSign;
    @BindView(R2.id.reporter_address)
    TextView reporterAddress;
    @BindView(R2.id.reporter_date)
    TextView reporterDate;
    @BindView(R2.id.reporter_layout)
    LinearLayout reporterLayout;
    @BindView(R2.id.vlog_layout)
    RelativeLayout vlogLayout;
    @BindView(R2.id.vlog_coverflow)
    RecyclerCoverFlow vlogCoverflow;
    @BindView(R2.id.live_layout)
    RelativeLayout liveLayout;
    @BindView(R2.id.live_recycler)
    RecyclerView liveRecycler;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    @BindView(R2.id.highlight_cover)
    ImageView highlightCover;
    @BindView(R2.id.highlight_title)
    TextView highlightTitle;
    @BindView(R2.id.vlog_divider)
    View divider;
    @BindView(R2.id.vlog_title)
    TextView vlogTitle;
    @BindView(R2.id.school_layout)
    CardView schoolLayout;
    @BindView(R2.id.point_layout)
    LinearLayout mPointLayout;
    @BindView(R2.id.school_navigation)
    GridViewPager schoolNavigation;

    private SchoolMainPresenter mPresenter;

    private SchoolMainBean mBean;

    private List<SchoolListBean> schoolList = new ArrayList<>();

    private CommonAdapter<NewsBean> highlightCommonAdapter;
    private List<NewsBean> highlightList = new ArrayList<>();

    private CoverFlowAdapter vlogCommonAdapter;
    private List<SchoolVlogBean> vlogList = new ArrayList<>();

    private CommonAdapter<TeleTextBean> liveCommonAdapter;
    private List<TeleTextBean> liveList = new ArrayList<>();

    private List<NewsBean> bannerList = new ArrayList<>();

    private ImageView[] imgs;//动态创建滑动指示器

    private static final int COLUMNS_NUM = 4;//导航栏列数
    private static final int ROWS_NUM = 2;//导航栏行数

    public static SchoolNewMainFragment newInstance() {
        SchoolNewMainFragment fragment = new SchoolNewMainFragment();
        return fragment;
    }


    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_school_main_new, null);
    }

    @Override
    protected void create() {
        loadMask.setStatus(LoadingLayout.Loading);

        mPresenter = new SchoolMainPresenter(this);

        refresh.setRefreshHeader(new MaterialHeader(getContext()));
        refresh.setEnableLoadMore(false);

        highlightRecycler.setLayoutManager(new GridLayoutManager(getContext(), 2));
        highlightRecycler.setAdapter(highlightCommonAdapter = new CommonAdapter<NewsBean>(getContext(), R.layout.item_school_new_home_highlight, highlightList) {
            @Override
            protected void convert(ViewHolder viewHolder, NewsBean newsBean, int i) {
                ImageView cover = viewHolder.getView(R.id.highlight_cover);
                Glide.with(SchoolNewMainFragment.this)
                        .load(newsBean.getLogo())
                        .apply(new RequestOptions().error(R.drawable.cover_large_default).placeholder(R.drawable.cover_large_default))
                        .into(cover);

                viewHolder.setText(R.id.highlight_title, newsBean.getTitle());
            }
        });

        vlogCoverflow.setLoop();
        vlogCoverflow.set3DItem(true);
        vlogCoverflow.setIntervalRatio(0.3f);
        vlogCoverflow.setAdapter(vlogCommonAdapter = new CoverFlowAdapter(getActivity()));


        liveRecycler.setLayoutManager(new GridLayoutManager(getContext(), 2));
        liveRecycler.setAdapter(liveCommonAdapter = new CommonAdapter<TeleTextBean>(getContext(), R.layout.item_school_new_home_live, liveList) {
            @Override
            protected void convert(ViewHolder viewHolder, TeleTextBean teleTextBean, int i) {
                RoundedImageView cover = viewHolder.getView(R.id.cover);
                Glide.with(SchoolNewMainFragment.this)
                        .load(teleTextBean.getCoverPic())
                        .apply(new RequestOptions().error(R.drawable.cover_large_default).placeholder(R.drawable.cover_large_default))
                        .into(cover);

                viewHolder.setText(R.id.title, teleTextBean.getTitle());

                switch (teleTextBean.getStatus()) {
                    case "2":
                        viewHolder.setVisible(R.id.live_tag, true);
                        viewHolder.setImageResource(R.id.live_tag, R.drawable.school_new_home_live_live);
                        break;
                    case "7":
                        viewHolder.setVisible(R.id.live_tag, true);
                        viewHolder.setImageResource(R.id.live_tag, R.drawable.school_new_home_live_review);
                        break;
                    default:
                        viewHolder.setVisible(R.id.live_tag, false);
                        break;
                }
            }
        });

        mPresenter.getData();
    }

    @Override
    protected void setListener() {
        //导航栏滑动监听
        schoolNavigation.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                setIndicator(position);//设置滑动指示器
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View view) {
                loadMask.setReloadButtonText("加载中...");
                mPresenter.getData();
            }
        });

        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mPresenter.getData();
            }
        });

        banner.setOnItemClickListener(new XBanner.OnItemClickListener() {
            @Override
            public void onItemClick(XBanner xBanner, Object o, View view, int position) {
                newsSkip(bannerList.get(position));
            }
        });

        highlightCommonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                newsSkip(highlightList.get(i));
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                return false;
            }
        });

        vlogCommonAdapter.setOnClickListener(new CoverFlowAdapter.onItemClick() {
            @Override
            public void clickItem(int position) {
                Bundle bundle = new Bundle();
                bundle.putSerializable("bean", (Serializable) vlogList);
                ARouter.getInstance()
                        .build(ARouterPathConstant.SCHOOL_VLOG_PLAY)
                        .withBundle("list", bundle)
                        .withInt("position", position)
                        .withInt("type", 1)
                        .navigation();
            }
        });

        liveCommonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                ARouter.getInstance()
                        .build(ARouterPathConstant.TELE_VIDEO_ACTIVITY)
                        .withString("id", mBean.getLiveList().get(i).getId() + "")
                        .navigation();
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                return false;
            }
        });

        vlogCoverflow.setOnItemSelectedListener(new CoverFlowLayoutManger.OnSelected() {
            @Override
            public void onItemSelected(int position) {
                vlogTitle.setText(vlogList.get(position).getInfo());
            }
        });

    }

    @Override
    protected void onFirstVisible() {

    }

    @Override
    protected void onVisible() {

    }

    @Override
    protected void onHide() {

    }

    //设置滑动指示器
    private void setIndicator(int position) {
        for (int i = 0; i < imgs.length; i++) {
            if (i == position) {
                imgs[i].setImageResource(R.drawable.school_navigation_indicator_on);
            } else {
                imgs[i].setImageResource(R.drawable.school_navigation_indicator_off);
            }
        }
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void setData(SchoolMainBean bean) {
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~");
        refresh.finishRefresh();

        mBean = bean;

        //顶部轮播
        if (mBean.getCarousel() != null && mBean.getCarousel().size() > 0) {
            banner.setVisibility(View.VISIBLE);

            bannerList.clear();
            bannerList.addAll(mBean.getCarousel());

            banner.setPageTransformer(Transformer.Scale);
            banner.offsetTopAndBottom(10);
            banner.setData(R.layout.item_school_new_home_banner, mBean.getCarousel(), null);
            banner.loadImage(new XBanner.XBannerAdapter() {
                @Override
                public void loadBanner(XBanner xBanner, Object model, View view, int i) {
                    RoundedImageView bannerCover = view.findViewById(R.id.cover);
                    Glide.with(SchoolNewMainFragment.this)
                            .load(((NewsBean) model).getLogo())
                            .apply(new RequestOptions().placeholder(R.drawable.cover_normal_default).error(R.drawable.cover_normal_default))
                            .into(bannerCover);
                }
            });
        } else {
            banner.setVisibility(View.GONE);
        }

        //精彩看点
        if (mBean.getHighLightList() != null && mBean.getHighLightList().size() > 0) {
            highlightContent.setVisibility(View.VISIBLE);
            highlightLayout.setVisibility(View.VISIBLE);

            Glide.with(getActivity().getApplicationContext())
                    .load(mBean.getHighLightList().get(0).getLogo())
                    .apply(new RequestOptions().placeholder(R.drawable.cover_normal_default).error(R.drawable.cover_normal_default))
                    .into(highlightCover);

            highlightTitle.setText(mBean.getHighLightList().get(0).getTitle());

            if (mBean.getHighLightList().size() > 1) {
                highlightList.clear();
                if (mBean.getHighLightList().size() > 5) {
                    for (int i = 1; i < 5; i++) {
                        highlightList.add(mBean.getHighLightList().get(i));
                    }
                } else {
                    for (int i = 1; i < mBean.getHighLightList().size(); i++) {
                        highlightList.add(mBean.getHighLightList().get(i));
                    }
                }

                highlightCommonAdapter.notifyDataSetChanged();
            }
        } else {
            highlightContent.setVisibility(View.GONE);
            highlightLayout.setVisibility(View.GONE);
        }

        //学校
        if (mBean.getSchoolList() != null && mBean.getSchoolList().size() > 0) {
            schoolLayout.setVisibility(View.VISIBLE);
            columnLayout.setVisibility(View.VISIBLE);
            mPointLayout.setVisibility(View.VISIBLE);

            schoolList = mBean.getSchoolList();
            schoolNavigation.setGridViewPagerDataAdapter(new GridViewPagerDataAdapter<SchoolListBean>(schoolList, ROWS_NUM, COLUMNS_NUM) {
                @Override
                public BaseAdapter getGridViewAdapter(List<SchoolListBean> currentList, int pageIndex) {
                    return new SchoolGridViewAdapter(getContext(), currentList);
                }

                @Override
                public void onItemClick(AdapterView parent, View view, int position, long id, int pageIndex) {
                    int mPosition = pageIndex * COLUMNS_NUM * ROWS_NUM + position;
                    SchoolListBean bean = schoolList.get(mPosition);
                    ARouter.getInstance()
                            .build(ARouterPathConstant.SCHOOL_COLUMN_DETAIL)
                            .withInt("schoolId", bean.getId())
                            .navigation();
                }
            });

            mPointLayout.removeAllViewsInLayout();


            imgs = new ImageView[schoolNavigation.getPageCount()];
            if (imgs.length < 2) {
                mPointLayout.setVisibility(View.GONE);
            } else {
                for (int i = 0; i < schoolNavigation.getPageCount(); i++) {
                    imgs[i] = new ImageView(getActivity());
                    if (i == 0) {
                        imgs[i].setImageResource(R.drawable.school_navigation_indicator_on);
                    } else {
                        imgs[i].setImageResource(R.drawable.school_navigation_indicator_off);
                    }
                    imgs[i].setPadding(2, 0, 2, 0);
                    mPointLayout.addView(imgs[i]);
                }
            }
        } else {
            schoolLayout.setVisibility(View.GONE);
            columnLayout.setVisibility(View.GONE);
            mPointLayout.setVisibility(View.GONE);
        }

        //小记者团
        if (mBean.getReportActivity() != null && mBean.getReportActivity().getId() != 0) {
            reporterLayout.setVisibility(View.VISIBLE);

            reporterTitle.setText(mBean.getReportActivity().getTitle());
            reporterAddress.setText(mBean.getReportActivity().getAddress());
            reporterNum.setText(mBean.getReportActivity().getReportCount() + "个小伙伴");

            reporterSign.setVisibility(View.GONE);
            if (mBean.getReportActivity().isReportOver()) {
                reporterTag.setImageResource(R.drawable.school_new_home_reporter_end_tag);
            } else if (mBean.getReportActivity().isReportNotStart()) {
                reporterTag.setImageResource(R.drawable.school_new_home_reporter_forecast_tag);
            } else {
                reporterTag.setImageResource(R.drawable.school_new_home_reporter_tag);
            }

            if (StringUtils.isNotEmpty(mBean.getReportActivity().getEndDate())) {
                reporterDate.setText(mBean.getReportActivity().getStartDate() + "—" + mBean.getReportActivity().getEndDate());
            } else {
                reporterDate.setText(mBean.getReportActivity().getStartDate());
            }

            Glide.with(SchoolNewMainFragment.this)
                    .load(mBean.getReportActivity().getLogo())
                    .apply(new RequestOptions().error(R.drawable.cover_large_default).placeholder(R.drawable.cover_large_default))
                    .into(reporterCover);

        } else {
            reporterLayout.setVisibility(View.GONE);
        }

        //vlog
        if (mBean.getVlogList() != null && mBean.getVlogList().size() > 0) {
            vlogLayout.setVisibility(View.VISIBLE);
            vlogCoverflow.setVisibility(View.VISIBLE);
            divider.setVisibility(View.VISIBLE);

            vlogList.clear();
            vlogList.addAll(mBean.getVlogList());
            vlogCommonAdapter.setListBean(vlogList);
            vlogCommonAdapter.notifyDataSetChanged();

            int index = mBean.getVlogList().size();
            if (index % 2 == 0) {
                vlogCoverflow.scrollToPosition(index / 2);
            } else {
                vlogCoverflow.scrollToPosition(index / 2 + 1);
            }

        } else {
            divider.setVisibility(View.GONE);
            vlogLayout.setVisibility(View.GONE);
            vlogCoverflow.setVisibility(View.GONE);
        }


        //直播
        if (mBean.getLiveList() != null && mBean.getLiveList().size() > 0) {
            liveRecycler.setVisibility(View.VISIBLE);
            liveLayout.setVisibility(View.VISIBLE);

            liveList.clear();
            liveList.addAll(mBean.getLiveList());
            liveCommonAdapter.notifyDataSetChanged();
        } else {
            liveRecycler.setVisibility(View.GONE);
            liveLayout.setVisibility(View.GONE);
        }
    }

    @Override
    public void setError(String msg) {
        loadMask.setReloadButtonText("点击重试~");
        loadMask.setStatus(LoadingLayout.Error);
        refresh.finishRefresh();
        if (!NetUtil.isNetworkAvalible(getContext())) {
            loadMask.setErrorImage(R.drawable.error_network);
            loadMask.setErrorText("网络异常，请检查您的网络！");
        } else if (msg.contains("暂无")) {
            loadMask.setErrorImage(R.drawable.empty_content);
            loadMask.setErrorText(msg);
        } else {
            loadMask.setErrorImage(R.drawable.error_content);
            loadMask.setErrorText(msg);
        }
    }

    @Override
    public void signResult(boolean isSuccess, String msg) {
        dismissLoading();
        showToast(msg, 4);
        reporterSign.setEnabled(true);
    }


    @OnClick({R2.id.camera, R2.id.scan, R2.id.search, R2.id.highlight_more, R2.id.highlight_cover, R2.id.reporter_sign,
            R2.id.reporter_cover, R2.id.column_more, R2.id.reporter_more, R2.id.vlog_more, R2.id.live_more, R2.id.back_btn})
    public void onClick(View view) {
        int viewId = view.getId();
        if (viewId == R.id.camera) {
        } else if (viewId == R.id.scan) {
        } else if (viewId == R.id.search) {
            RouterManager.router(ARouterPathConstant.SCHOOL_SEARCH);
        } else if (viewId == R.id.highlight_more) {
            ARouter.getInstance()
                    .build(ARouterPathConstant.NEWS_LIST)
                    .withString("title", "精彩看点")
                    .withString("id", mBean.getJckdCatalogId() + "")
                    .navigation();
        } else if (viewId == R.id.highlight_cover) {
            newsSkip(mBean.getHighLightList().get(0));
        } else if (viewId == R.id.column_more) {
            RouterManager.router(ARouterPathConstant.SCHOOL_COLUMN);
        } else if (viewId == R.id.reporter_more) {
            ARouter.getInstance()
                    .build(ARouterPathConstant.SCHOOL_REPORTER_ACT_LIST)
                    .withString("title", "小记者团活动")
                    .navigation();
        } else if (viewId == R.id.vlog_more) {
            RouterManager.router(ARouterPathConstant.SCHOOL_VLOG);
        } else if (viewId == R.id.live_more) {
            ARouter.getInstance()
                    .build(ARouterPathConstant.TELETEXT_LIST)
                    .withString("title", "校园直播")
                    .withString("type", "4")
                    .withBoolean("isHome", true)
                    .navigation();
        } else if (viewId == R.id.reporter_cover) {
            ARouter.getInstance()
                    .build(ARouterPathConstant.SCHOOL_REPORTER_ACT_DETAIL)
                    .withInt("actId", mBean.getReportActivity().getId())
                    .navigation();
        } else if (viewId == R.id.reporter_sign) {
            reporterSign.setEnabled(false);
            CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                @Override
                public void login(boolean isLogin) {
                    if (isLogin) {
                        showLoading();
                        String username = CommonUtils.getInstance().getUserName();
                        mPresenter.doSign(username, mBean.getReportActivity().getId());
                    } else {
                        Toasty.normal(getContext(), "尚未登录或登录已失效！").show();
                        RouterManager.routerLogin(getActivity(), 0);
                        reporterSign.setEnabled(true);
                    }
                }

                @Override
                public void error(String s) {
                    reporterSign.setEnabled(true);
                }
            });
        } else if (viewId == R.id.back_btn) {
            if (getActivity() instanceof SchoolHomeActivity) {
                ((SchoolHomeActivity) getActivity()).doFinish();
            }
        }
    }

    private void newsSkip(NewsBean bean) {
        switch (bean.getType()) {
            case "1"://普通新闻
            {
                Bundle bundle = new Bundle();
                bundle.putString("id", bean.getID());
                RouterManager.router(ARouterPathConstant.NORMAL_NEWS_ACTIVITY, bundle);
            }
            break;
            case "2"://图片新闻
            {
                Bundle bundle = new Bundle();
                bundle.putString("id", bean.getID());
                bundle.putString("section", bean.getCatalogID());
                RouterManager.router(ARouterPathConstant.PICTURE_NEWS_ACTIVITY, bundle);
            }

            break;
            case "3"://直播
            {
                Bundle bundle = new Bundle();
                bundle.putString("newsId", bean.getID());
                bundle.putString("liveType", bean.getLivetype());
                RouterManager.router(ARouterPathConstant.LIVE_NORMAL_ACTIVITY, bundle);
            }
            break;
            case "4"://标题新闻
            {
                Bundle bundle = new Bundle();
                bundle.putString("id", bean.getID());
                bundle.putString("title", bean.getTitle());
                bundle.putString("url", bean.getRedirectURL());
                RouterManager.router(ARouterPathConstant.ADV, bundle);
            }
            break;
            case "5"://视频新闻
            {
                Bundle bundle = new Bundle();
                bundle.putString("id", bean.getID());
                RouterManager.router(ARouterPathConstant.VIDEO_NEWS_ACTIVITY, bundle);
            }
            break;
            case "8"://互动直播
                break;
            case "101"://抓取新闻
            {
                Bundle bundle = new Bundle();
                bundle.putString("id", bean.getID());
                RouterManager.router(ARouterPathConstant.NEWS_CATCH, bundle);
            }
            break;
            default:
                break;

        }
    }

}
